package com.ynu.springbootappdemo.service;

import com.ynu.springbootappdemo.model.entity.User;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.ynu.springbootappdemo.common.constant.CommonConstant.*;

@Service
public class TokenService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 从缓存中获取Token，如果缓存中没有则从Redis中获取
     * @param userPhone 用户手机
     * @param tokenType Token类型（access_token 或 refresh_token）
     * @return Token字符串
     */
    @Cacheable(value = "tokens", key = "#userPhone + #tokenType")
    public String getCachedToken(String userPhone, String tokenType) {
        return (String) redisTemplate.opsForValue().get(userPhone + tokenType);
    }

    /**
     * 更新缓存中的Token，同时设置Redis中Token的过期时间
     * @param user 用户对象
     * @param token Token字符串
     * @param tokenType Token类型（access_token 或 refresh_token）
     * @return 更新后的Token字符串
     */
    @CachePut(value = "tokens", key = "#user.userPhone + #tokenType")
    public String updateCachedToken(User user, String token, String tokenType) {
        if (ACCESS_TOKEN.equals(tokenType)){
            redisTemplate.opsForValue().set(user.getUserPhone() + ACCESS_TOKEN, token, ACCESS_Token_EXPIRE_TIME, TimeUnit.DAYS);
        } else if (REFRESH_TOKEN.equals(tokenType)) {
            redisTemplate.opsForValue().set(user.getUserPhone() + REFRESH_TOKEN, token, REFRESH_Token_EXPIRE_TIME, TimeUnit.DAYS);
        }
        return token;
    }
}
